<?php
function TVBGetAuthUserFromCookie() {
	if (!isset($_COOKIE['A'])) {
		return FALSE;
	}
	// Check login cookie and expire time
	$encoded = $_COOKIE['A'];
	$tmp = json_decode($encoded, TRUE);
	if (count($tmp) != 4) {
		return FALSE;
	}

	$userId = $tmp[0];
	$expire = $tmp[1];
	$rand = $tmp[2];
	$encodedSig = $tmp[3];
	$sig = base64_decode($encodedSig);

	if (!TVBAuthVerify($userId, $expire, $rand, $sig)) {
		return FALSE;
	}

	if ($expire < time()) {
		return FALSE;
	}
	
	return $userId;
}

function TVBAuthSign($userId, $expire, $rand) {
	$fp = fopen("/data/auth/key/key.pem", "r");
	$priv_key = fread($fp, 8192);
	fclose($fp);
	$pkeyid = openssl_get_privatekey($priv_key);

	// compute signature
	$data = "{$userId}\001{$expire}\001{$rand}";
	openssl_sign($data, $signature, $pkeyid);

	// free the key from memory
	openssl_free_key($pkeyid);

	return $signature;
}

function TVBAuthVerify($userId, $expire, $rand, $signature) {
	$fp = fopen("/data/auth/key/cert.pem", "r");
	$cert = fread($fp, 8192);
	fclose($fp);
	$pubkeyid = openssl_get_publickey($cert);

	// state whether signature is okay or not
	$data = "{$userId}\001{$expire}\001{$rand}";
	$ok = openssl_verify($data, $signature, $pubkeyid);
	// free the key from memory
	openssl_free_key($pubkeyid);
	
	return ($ok == 1);
}

function TVBSetAuthCookie($userId) {
	$rand = rand(1, 1000000);
	$expire = time() + 86400;
	$sig = TVBAuthSign($userId, $expire, $rand);
	$encodedSig = base64_encode($sig);
	$value = array($userId, $expire, $rand, $encodedSig);
	$encoded = json_encode($value);

	$ret = setcookie('A', $encoded, 0, '/', 'tvb.com');
	
	return $ret;
}

function TVBAuthenticateUser($userId, $password, $methods) {
	$LDAP = $methods[0];
	$DB = $methods[1];
	foreach ($methods as $method) {
		switch ($method) {
		case 'LDAP':
			$ldapAuth = new LDAPAuthenticator();
			$ret = $ldapAuth->authenticate($userId, $password);
			if($ret){
				return $ret;
			}
			break;
		case 'DB':
			$dbAuth = new DBAuthenticator();
			$ret = $dbAuth->authenticate($userId, $password);
			if($ret){
				return $ret;
			}
			break;
		}
	}
}
?>
